package com.atguigu.ssyx.common.service;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 杨林
 * @create 2023-08-02 17:03 星期三
 * description:
 */
@Service
public class RabbitService {
    
    //引入rabbitmq模板
    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 
     * @param exchange：交换机
     * @param routingKey：路由key
     * @param message：消息
     * @return
     */
    public Boolean sendMessage(String exchange,String routingKey,Object message){
        //调用发送消息的方法
        rabbitTemplate.convertAndSend(exchange,routingKey,message);
        return true;
    }


    /**
     * 
     * @param exchange：交换机
    * @param routingKey：路由key
     * @param message：消息
     * @param delayTime：延迟时间   单位：秒
     * @return
     */
    public Boolean sendDelayMessage(String exchange,String routingKey,Object message,int delayTime){
        //在发送消息的时候设置延迟时间
        rabbitTemplate.convertAndSend(exchange, routingKey, message, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                //设置一个延迟时间
                message.getMessageProperties().setDelay(delayTime * 1000);
                return message;
            }
        });
        return true;
    }
    
}
